package com.telecomyt.jwportal.activity.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.telecomyt.jwportal.R;
import com.telecomyt.jwportal.activity.fragment.adapter.ContentAdapter;
import com.telecomyt.jwportal.activity.fragment.bean.Bean;
import com.telecomyt.jwportal.base.BaseActivity;
import com.telecomyt.jwportal.base.BasePresenter;
import com.telecomyt.jwportal.bean.UsersBean;
import com.telecomyt.jwportal.http.RequestParams;
import com.telecomyt.jwportal.http.RetrofitManager;
import com.telecomyt.jwportal.utils.ObjectSaveUtils;
import com.telecomyt.jwportal.utils.ToastUtils;
import com.telecomyt.jwportal.widget.FraToolBar;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class FragmentActivity extends BaseActivity {
    @BindView(R.id.mContentRecycle)
    RecyclerView mContentRecycle;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.mFrameLayout)
    FrameLayout mFrameLayout;
    @BindView(R.id.mBtnClear)
    Button mBtnClear;
    @BindView(R.id.mTextView)
    TextView mTextView;
    @BindView(R.id.mFraToolBar)
    FraToolBar mFraToolBar;
    private int count = 0;
    List<Bean> list = new ArrayList<>();
    private MyAdapter adapter;
    private DemoFragment fragment;
    FragmentManager.OnBackStackChangedListener listener;
    private ContentAdapter contentAdapter;
    private int number = 0;//总人数

    public static void start(Context context) {
        Intent starter = new Intent(context, FragmentActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_fragment;
    }

    @Override
    protected void initView() {
        mFraToolBar.setLeftFinish(this);
        mContentRecycle.setLayoutManager(new LinearLayoutManager(this));
        contentAdapter = new ContentAdapter(R.layout.fragment_content_items);
        mContentRecycle.setAdapter(contentAdapter);
        contentAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                showData(contentAdapter.getData().get(position).getDeptId(), true, contentAdapter.getData().get(position).getDeptName());
            }
        });
        contentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.mCheckBox:
                        contentAdapter.getData().get(position).setCheck(!contentAdapter.getData().get(position).isCheck());
                        statisticsNumber();
                        break;
                }
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        adapter = new MyAdapter(R.layout.fragment_items, list);
        mRecyclerView.setAdapter(adapter);


        findViewById(R.id.myTextView1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchFragment(count, null, "");
                count++;
            }
        });

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                FragmentManager manager = getSupportFragmentManager();
                manager.popBackStack("fragment" + position, 0);
                count = position + 1;
                clearList(position);
            }
        });
        FragmentManager manager = getSupportFragmentManager();
        listener = new FragmentManager.OnBackStackChangedListener() {

            @Override
            public void onBackStackChanged() {
                Log.d("qijian", "backstack changed");
            }
        };
        manager.addOnBackStackChangedListener(listener);

    }

    /**
     * @date: 2020/8/29
     * @author: chengDa
     * @description: 请求列表数据
     */
    public void showData(int deptId, boolean isAddFragment, String TabName) {

        Observable<UsersBean> localDataObservable = Observable.create((ObservableOnSubscribe<UsersBean>)
                sub -> {
                    UsersBean cacheData = null;
                    try {
                        cacheData = (UsersBean) ObjectSaveUtils.getObject(getContext(), "user_cache");   //读取数据对象
                    } catch (Exception e) {

                    }
                    if (cacheData != null) {
                        sub.onNext(cacheData);
                    }
                    sub.onComplete();
                })
                .subscribeOn(Schedulers.io());
        Observable<UsersBean> remoteDataObservable = RetrofitManager.getInstance()
                .getDefaultReq()
                .users(new RequestParams().put("detail", true).put("deptId", deptId).getBody())
                .subscribeOn(Schedulers.io())
                .map(dataResponse -> {
                    UsersBean data = dataResponse.getData();
                    if (data != null && data.getDepts() != null && data.getDepts().size() > 0) {
                        ObjectSaveUtils.saveObject(getContext(), "user_cache", data);   //保存数据对象
                    }
                    return data;
                });
        Observable.concat(localDataObservable, remoteDataObservable)
                .firstElement()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<UsersBean>() {
                    @Override
                    public void accept(UsersBean usersBean) throws Exception {
                        if (usersBean != null && usersBean.getDepts() != null) {
                            if (usersBean.getDepts().size() > 0) {
                                if (isAddFragment) {
                                    mContentRecycle.setVisibility(View.GONE);
                                    switchFragment(count, usersBean.getDepts(), TabName);
                                    count++;
                                } else {
                                    contentAdapter.setNewData(usersBean.getDepts());
                                }
                            } else {
                                ToastUtils.showShort("暂时没有下级数据了~");
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
//        RetrofitManager.getInstance()
//                .getDefaultReq()
//                .users(new RequestParams().put("detail", true).put("deptId", deptId).getBody())
//                .compose(RxHelper.observableIOMain(this))
//                .subscribe(new MyObserver<UsersBean>(this) {
//                    @Override
//                    public void onSuccess(UsersBean data) {
//                        if (data != null && data.getDepts() != null) {
//                            if (data.getDepts().size() > 0) {
//                                if (isAddFragment) {
//                                    mContentRecycle.setVisibility(View.GONE);
//                                    switchFragment(count, data.getDepts(), TabName);
//                                    count++;
//                                } else {
//                                    contentAdapter.setNewData(data.getDepts());
//                                }
//                            } else {
//                                ToastUtils.showShort("暂时没有下级数据了~");
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(Throwable e, String errorMsg) {
//
//                    }
//                });
    }
//new Observer<UsersBean>() {
//        @Override
//        public void onSubscribe(Disposable d) {
//        }
//
//        @Override
//        public void onNext(UsersBean bean) {
//            if (bean != null && bean.getData() != null && bean.getData().getDepts() != null) {
//                if (bean.getData().getDepts().size() > 0) {
//                    if (isAddFragment) {
//                        mContentRecycle.setVisibility(View.GONE);
//                        switchFragment(count, bean.getData().getDepts(), TabName);
//                        count++;
//                    } else {
//                        contentAdapter.setNewData(bean.getData().getDepts());
//                    }
//                } else {
//                    ToastUtils.showShort("暂时没有下级数据了~");
//                }
//            }
//            dismissLoading();
//
//        }
//
//        @Override
//        public void onError(Throwable e) {
//            dismissLoading();
//
//        }
//
//        @Override
//        public void onComplete() {
//            dismissLoading();
//        }
//    }

    /**
     * 清除list
     */
    private void clearList(int position) {
        int pos = position + 1;
        int size = list.size();
        if (pos < size) {
            int count = size - pos;
            for (int i = 0; i < count; i++) {
                list.remove(pos);
            }
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 添加fragment
     */
    private void switchFragment(int pressCount, List<UsersBean.DeptsBean> listBeans, String TabName) {
        Bean bean = new Bean();
        bean.setCount(TabName);
        list.add(bean);
        mRecyclerView.scrollToPosition(list.size() - 1);
        adapter.notifyDataSetChanged();
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        fragment = new DemoFragment(this);
        Bundle bundle = new Bundle();
        bundle.putString("number", String.valueOf(pressCount));
        bundle.putSerializable("bean", (Serializable) listBeans);
        fragment.setArguments(bundle);
        fragmentTransaction.replace(R.id.mFrameLayout, fragment);
        fragmentTransaction.addToBackStack("fragment" + pressCount);
        fragmentTransaction.commit();
    }

    /**
     * @date: 2020/8/29
     * @author: chengDa
     * @description: 计算人数
     */
    public void statisticsNumber() {
        for (int i = 0; i < contentAdapter.getData().size(); i++) {
            if (contentAdapter.getData().get(i).isCheck()) {
                number += contentAdapter.getData().get(i).getUserCount();
            }
        }
        mTextView.setText(String.format("已选:%s人", number));
    }

    @Override
    protected void initData() {
        showData(280, false, "");
    }

    @Override
    protected BasePresenter creatPresenter() {
        return null;
    }


    @OnClick(R.id.mBtnClear)
    public void onViewClicked() {
        for (int i = 0; i < contentAdapter.getData().size(); i++) {
            contentAdapter.getData().get(i).setCheck(false);
        }
        contentAdapter.notifyDataSetChanged();
        number = 0;
        mTextView.setText("已选:0人");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    private class MyAdapter extends BaseQuickAdapter<Bean, BaseViewHolder> {
        public MyAdapter(int layoutResId, @Nullable List<Bean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, Bean item) {
            TextView myTextView1 = helper.getView(R.id.myTextView1);
            if (helper.getLayoutPosition() == 0) {
                myTextView1.setCompoundDrawables(null, null, null, null);
            } else {
                Drawable drawable = getResources().getDrawable(R.drawable.call_log_into);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                        drawable.getMinimumHeight());
                myTextView1.setCompoundDrawables(drawable, null, null, null);
            }
            myTextView1.setText(item.getCount());
        }
    }

    /**
     * 返回键监听
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (list != null && list.size() > 0) {
            if (list.size() == 1) {
                list.remove(0);
                count = 0;
            } else {
                count--;
                list.remove(count);
            }
            adapter.notifyDataSetChanged();
            quitActivity();
        }
    }

    /**
     * 退出activity Dialog
     */
    private void quitActivity() {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        int backStackEntryCount = supportFragmentManager.getBackStackEntryCount();
        if (backStackEntryCount == 0) {
            list.clear();
            adapter.notifyDataSetChanged();
            mContentRecycle.setVisibility(View.VISIBLE);
        }
//            AlertDialog.Builder builder = new AlertDialog.Builder(this);
//            builder.setMessage("确认退出么?");
//            builder.setTitle("提示");
//            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                    finish();
//                }
//            });
////            builder.setNegativeButton("否", null);
//            builder.show();
//        }
    }

    protected void onDestroy() {
        super.onDestroy();
        FragmentManager manager = getSupportFragmentManager();
        manager.removeOnBackStackChangedListener(listener);
    }
}
